<?php
/**
* 优惠券模块 工具类
*
* 优惠券模块 工具类的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\Coupons;

use Illuminate\Support\Facades\DB;
use App\Services\Tool\DataBase\SQL;
use Log;
use App\Services\ProductsService\ProductTool;
use App\Services\Tool\GeneralTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\BrandService\BrandToolService;

class CouponsTool{

    function __construct(ProductTool $productTool,
                         ProductTempTool $productTempTool,
                         BrandToolService $brandToolService){
        $this->productTool     = $productTool;
        $this->productTempTool = $productTempTool;
        $this->brandToolService= $brandToolService;
    }

    /**
        我的优惠券列表
     */
    function myCouponsList($input,$order='end_time',$sort='asc'){
        $time = time();
        $coupons = [];
        switch($input['type']){
            case 'canUse':
                $input['where']['using_time'] = 0;
                $coupons = DB::table('coupons')
                           ->where($input['where'])
                           ->where('end_time','>',$time)
                           ->orderBy($order,$sort)
                           ->select('coupon_id','channel_id','price','using_time','user_id','end_time','begin_time','end_time','state')
                           ->paginate($input['per_page'])
                           ->toArray();
                break;
            case 'invalid':
                $input['where']['using_time'] = 0;
                $coupons = DB::table('coupons')
                           ->where($input['where'])
                           ->where('end_time','<',$time)
                           ->orderBy($order,$sort)
                           ->select('coupon_id','channel_id','price','using_time','user_id','end_time','begin_time','end_time','state')
                           ->paginate($input['per_page'])
                           ->toArray();
                break;
            case 'used':
                $coupons = DB::table('coupons')
                           ->where($input['where'])
                           ->where('using_time','>',0)
                           ->orderBy($order,$sort)
                           ->select('coupon_id','channel_id','price','using_time','user_id','end_time','begin_time','end_time','state')
                           ->paginate($input['per_page'])
                           ->toArray();
                break;
        }
        $coupons['total_page'] = isset($coupons['last_page'])?$coupons['last_page']:0;
        //dd($coupons);
        foreach($coupons['data'] as $cou){
            $channel    = $this->getCouponChannel(['channel_id'=>$cou->channel_id]);
            $cou->name  = isset($channel->name)?$channel->name:'';
            $cou->desc  = isset($channel->desc)?$channel->desc:'';
            $cou->coupon_type   = isset($channel->coupon_type) ? $channel->coupon_type : 1;
            $cou->time_str      = (isset($cou->begin_time)?date('Y.m.d',$cou->begin_time):'').'至'.(isset($cou->end_time)?date('Y.m.d',$cou->end_time):'');
            $cou->binding_type  = isset($channel->binding_type)?$channel->binding_type:1;
            if($cou->using_time!=0)
                $cou->state = 2;
            else if($cou->end_time<=time())
                $cou->state = 3;
        }
        return $coupons;
    }
    /**
        获取用户优惠券渠道编号
     */
    function get_my_coupon_channel_id_list($input){
        $time = time();
        $channel_id = DB::table('coupons')
                      ->where($input)
                      ->where('begin_time','<',$time)
                      ->where('end_time','>',$time)
                      ->pluck('channel_id')
                      ->toArray();
        return array_unique($channel_id);
    }

    /**
        获取购物车可用渠道
     */
    function get_shop_car_can_use_from_channel($channel_id_list,$user_id){
        $id  = [] ;
        $arr = [] ;

        foreach($channel_id_list as $channel_id){
            $channel_maps = $this->get_channel_maps($channel_id);
            Log::info($channel_maps);
            $result       = $this->channel_is_vaild_from_shop_car($channel_maps,$user_id);
            if($result['is_valid']){
                $id[] = $channel_id;
                $arr[$channel_id.'']        = GeneralTool::priceFormat($result['discount']);
                $arr[$channel_id.'_detail'] = ['type'=>$result['type'],'reg_id'=>$result['reg_id']];
            }
        }
        return ['channel_id'=>$id,'result'=>$arr];
    }

    /**
        获取购物车优惠券列表
     */
    function get_shop_car_coupons_paginate($result,$input,$total){

        $coupons = DB::table('coupons')
                   ->where($input['where'])
                   ->whereIn('channel_id',$result['channel_id'])
                   ->orderBy('price','desc')
                   ->paginate($input['per_page'])
                   ->toArray();

        $coupons['total_page'] = $coupons['last_page'];
        foreach($coupons['data'] as $coupon){
            $channel                = $this->getCouponChannel(['channel_id'=>$coupon->channel_id]);
            $coupon->coupon_type    = isset($channel->coupon_type) ? $channel->coupon_type : 1;
            $coupon->name           = isset($channel->name)?$channel->name:'';
            $coupon->desc           = isset($channel->desc)?$channel->desc:'';
            $coupon->time_str       =
                                      (isset($coupon->begin_time)?date('Y.m.d',$coupon->begin_time):'').
                                      '至'.
                                      (isset($coupon->end_time)?date('Y.m.d',$coupon->end_time):'');
            $coupon->binding_type   = isset($channel->binding_type)?$channel->binding_type:1;
            if($coupon->using_time != 0)
                $coupon->state = 2;
            else if($coupon->end_time <= time())
                $coupon->state = 3;

            $coupon->discount_price = isset($result['result'][$coupon->channel_id]) ? $result['result'][$coupon->channel_id] : '0';
            $coupon->total_fee      = GeneralTool::priceFormat($total - $coupon->discount_price) . '';
        }

        return $coupons;
    }

    /**
        获取立即购买优惠券列表
     */
    function get_buy_now_can_use_from_channel($channel_id_list,$input){
        $id  = [] ;
        $arr = [] ;
        $input['product_temp_id'] = $this->getTemplateByProductId($input['product_id']);
        if(!isset($input['product_id'])) return ['channel_id'=>$id,'result'=>$arr];
        $input['brand_id'] = $this->get_brand_id_by_prod_temp_id($input['product_temp_id']);
        if(!isset($input['product_temp_id'])) return ['channel_id'=>$id,'result'=>$arr];

        foreach($channel_id_list as $channel_id){
            $channel_maps = $this->get_channel_maps($channel_id);
            Log::info($channel_maps,$input);
            $result       = $this->channel_is_vaild_from_buy_now($channel_maps,$input);
            if($result['is_valid']){
                $id[] = $channel_id;
                $arr[$channel_id.''] = GeneralTool::priceFormat($result['discount']);
                $arr[$channel_id.'_detail'] = ['type'=>$result['type'],'reg_id'=>$result['reg_id']];
            }
        }
        return ['channel_id'=>$id,'result'=>$arr];
    }

    //工具
    //获取立即购买可用渠道编号数组
    function channel_is_vaild_from_buy_now($channel_maps,$input){
        $arr['is_valid'] = 0;
        $total_fee    = $input['total_fee'];
        $resource_fee = $this->get_product_temp_price_by_product_temp_id($input['product_id']) * $input['quantity'];
        foreach($channel_maps as $map){
            switch($map->type){
                case 0:
                    //额度
                    if($total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);
                        if(!isset($price)) continue;

                        $arr['is_valid'] = 1;
                        $arr['discount'] = $total_fee >= $price ? $price : $total_fee;
                        $arr['type']     = 0;
                        $arr['reg_id']   = '';
                        return $arr;
                    }
                    continue ;
                case 1:
                    //商品模版
                    if($map->reg_id == $input['product_temp_id'] && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);

                        if(!isset($price)) continue;
                        $arr['is_valid'] = 1;
                        $arr['discount'] = $resource_fee >= $price ? $price : $resource_fee;
                        $arr['type']     = 1;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;

                    }
                    continue ;
                case 2:
                    //商品
                    /*
                    if($map->reg_id == $input['product_id'] && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);

                        if(!isset($price)) continue;

                        $arr['is_valid'] = 1;
                        $arr['discount'] = $resource_fee >= $price ? $price : $resource_fee;
                        $arr['type']     = 2;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;

                    }
                    */
                    continue ;
                case 3:
                    //品牌

                    if($map->reg_id == $input['brand_id'] && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);
                        if(!isset($price)) continue;

                        $arr['is_valid'] = 1;
                        $arr['discount'] = $resource_fee >= $price ? $price : $resource_fee;
                        $arr['type']     = 3;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;

                    }
                    continue ;
            }
        }
        return $arr;
    }
    //获取用户购物车金额
    function get_shop_car_total_fee($input,$type = 1){
        $where  = ['user_id'=>$input['user_id'],
                   'is_select'=>1,
                   'state'=>1];
        if($type == 2) $where = $input;
        $cars   = SQL::get(array('table'=>'shop_cars',
                                 'where'=>$where));
        $total_fee        = 0;
        $total_postage    = 0;
        foreach($cars as $car){
            $result = $this->can_order($car->product_id,$car->colour_name,$car->size_name,$car->quantity,$input['user_id']);
            if(isset($car->is_select) && $car->is_select == 1 && isset($result) && isset($result['state']) &&
                ($result['state'] == 'M00000' || $result['state'] == 'M08025')){
                $price      = $this->get_product_price($car->product_id);
                $total_fee += $price * $car->quantity;
                if($type == 3){
                    $postage = $this->get_postage_by_product_temp_id($car->product_temp_id);
                    $total_postage += $postage;
                }
            }
        }
        if($type == 3) return $total_fee + $total_postage;
        return GeneralTool::priceFormat($total_fee).'';
    }
    //判断渠道优惠券范围是否包含购物车
    function channel_is_vaild_from_shop_car($channel_maps,$user_id){
        $arr['is_valid'] = 0;
        foreach($channel_maps as $map){
            Log::info((array)$map);
            switch($map->type){
                case 0:
                    //额度
                    $total_fee = $this->get_shop_car_total_fee(['user_id'=>$user_id]);
                    if($total_fee != 0 && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);
                        if(!isset($price)) continue;
                        $arr['is_valid'] = 1;
                        $arr['discount'] = $total_fee >= $price ? $price : $total_fee;
                        $arr['type']     = 0;
                        $arr['reg_id']   = '';
                        return $arr;
                    }
                    continue ;
                case 1:
                    $total_fee    = $this->get_shop_car_total_fee(['user_id'         => $user_id,
                                                                   'is_select'       => 1,
                                                                   'state'           => 1,
                                                                   'product_temp_id' => $map->reg_id],2);
                    //商品模版
                    $resource_fee = $this->get_shop_car_total_fee_by_resource(['user_id'         => $user_id,
                                                                               'is_select'       => 1,
                                                                               'state'           => 1,
                                                                               'product_temp_id' => $map->reg_id]);

                    if($total_fee != 0 && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);

                        if(!isset($price)) continue;
                        $arr['is_valid'] = 1;
                        $arr['discount'] = $resource_fee >= $price ? $price : $resource_fee;
                        $arr['type']     = 1;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;
                    }
                    continue ;
                case 2:
                    /*
                    //商品
                    $total_fee = $this->get_shop_car_total_fee_by_resource(['user_id'    => $user_id,
                                                                            'is_select'  => 1,
                                                                            'state'      => 1,
                                                                            'product_id' => $map->reg_id]);

                    if($total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);

                        if(!isset($price)) continue;
                        $arr['is_valid'] = 1;
                        $arr['discount'] = $total_fee >= $price ? $price : $total_fee;
                        $arr['type']     = 2;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;
                    }
                    */
                    continue ;
                case 3:
                    //品牌
                    $total_fee = $this->get_shop_car_total_fee_by_resource(['user_id'   => $user_id,
                                                                            'is_select' => 1,
                                                                            'state'     => 1,
                                                                            'brand_id'  => $map->reg_id]);
                    if($total_fee != 0 && $total_fee >= $map->quota){
                        $price = $this->get_price_by_channel($map->channel_id);
                        if(!isset($price)) continue;
                        $arr['is_valid'] = 1;
                        $arr['discount'] = $total_fee >= $price ? $price : $total_fee;
                        $arr['type']     = 3;
                        $arr['reg_id']   = $map->reg_id;
                        return $arr;
                    }
                    continue ;
            }
        }
        return $arr;
    }
    //获取优惠券对应范围金额
    function get_shop_car_total_fee_by_resource($input){
        $total_fee = 0;
        $cars   = SQL::get(array('table'=>'shop_cars',
                                 'where'=>$input));
        foreach($cars as $car){
            $result = $this->can_order($car->product_id,$car->colour_name,$car->size_name,$car->quantity,$input['user_id']);
            if(isset($car->is_select) && $car->is_select == 1 && isset($result) && isset($result['state']) &&
                ($result['state'] == 'M00000')){
                $price      = $this->get_product_temp_price_by_product_temp_id($car->product_id);
                $total_fee += $price * $car->quantity;
            }
        }

        return $total_fee;
    }
    //获取渠道优惠券金额
    function get_price_by_channel($channel_id){
        $price = SQL::pluck(['table' => 'channels',
                             'where' => ['channel_id'=>$channel_id],
                             'pluck' => 'price']);
        return $price;
    }
    //获取渠道关联
    function get_channel_maps($input){
        $maps = SQL::get(['table' => 'channel_maps',
                          'where' => ['channel_id' => $input,
                                      'state'      => 1],]);
        return $maps;
    }
    //获取优惠券渠道信息
    function getCouponChannel($input){
        $channel = DB::table('channels')
                   ->where($input)
                   ->first();
        return $channel;
    }
    //获取优惠券是否为单独使用字符串
    function getCouponRemark($input){
        switch($input){
            case 1:
                return '该券不能与其他活动叠加使用';
        }
        return '';
    }
    //判断作品是否可用该优惠券
    static function check($input){
        if(!isset($input['brand_id'])||!isset($input['create_id'])||!isset($input['product_id'])||!isset($input['coupon_id'])){
            return ['state'=>false,'message'=>'作品不存在'];
        }

        $channel_id = SQL::pluck(['table'=>'coupons',
                                  'where'=>['coupon_id'=>$input['coupon_id']],
                                  'pluck'=>'channel_id']);
        if(!isset($channel_id))
            return ['state'=>false,'message'=>'优惠券不存在'];

        //作品
        if(SQL::count(['table'=>'channel_maps',
                       'where'=>['type'=>2,
                                 'channel_id'=>$channel_id,
                                 'reg_id'=>$input['create_id'],
                                 'state'=>1]])>0)
            return ['state'=>true,'message'=>''];
        if(SQL::count(['table'=>'channel_maps',
                       'where'=>['type'=>1,
                                 'channel_id'=>$channel_id,
                                 'reg_id'=>$input['product_id'],
                                 'state'=>1]])>0)
            return ['state'=>true,'message'=>''];
        if(SQL::count(['table'=>'channel_maps',
                       'where'=>['type'=>3,
                                 'channel_id'=>$channel_id,
                                 'reg_id'=>$input['brand_id'],
                                 'state'=>1]])>0)
            return ['state'=>true,'message'=>''];
        return ['state'=>false,'message'=>'优惠券不可用于该作品'];
    }
    /**
        获取优惠券详情
     */
    function getCouponInfo($input){
        $coupon = DB::table('coupons')
                  ->where(['coupon_id'=>$input['coupon_id']])
                  ->select('coupon_id','channel_id','price','using_time','user_id','end_time','begin_time','end_time','state')
                  ->first();
        if(!isset($coupon)){
            return null;
        }
        $channel    = SQL::first(array('table'=>'channels',
                                       'where'=>array('channel_id'=>$coupon->channel_id)));
        $coupon->name   = isset($channel->name)?$channel->name:'';
        $coupon->desc   = isset($channel->desc)?$channel->desc:'';
        $coupon->coupon_type    = isset($channel->coupon_type) ? $channel->coupon_type : 1;
        $coupon->time_str =
                            (isset($coupon->begin_time)?date('Y.m.d',$coupon->begin_time):'').
                            '至'.
                            (isset($coupon->end_time)?date('Y.m.d',$coupon->end_time):'');
        $coupon->binding_type   = isset($channel->binding_type)?$channel->binding_type:1;
        if($coupon->using_time!=0)
            $coupon->state = 2;
        else if($coupon->end_time<=time())
            $coupon->state = 3;
        if(isset($channel)&&$channel->binding_type==2){
            $coupons = $this->getCouponChilds(['coupon_id'=>$coupon->coupon_id,'state'=>1]);
            $coupon->code = isset($coupons['code'])?$coupons['code']:'01';
            $coupon->coupons = isset($coupons['data'])?$coupons['data']:[];
        }else{
            $count = SQL::count(['table'=>'couponbindingcoupons',
                                 'where'=>['b_coupon_id'=>$coupon->coupon_id]]);

            if($count)
                $coupon->code = '02';
            else
                $coupon->code = '00';
            $coupon->coupons = [];
        }
        return $coupon;
    }

    /**
        获取可用优惠券渠道编号
     */
    function get_coupon_channel_id_by_coupon_id($input){
        $time = time();
        $channel_id = DB::table('coupons')
                      ->where($input)
                      ->where('begin_time','<',$time)
                      ->where('end_time','>',$time)
                      ->pluck('channel_id')
                      ->toArray();

        return $channel_id;
    }

    /**
        优惠券子集
     */
    function getCouponChilds($input){

        $arr    = [];
        $code   = '00';
        $coupons    = SQL::get(['table'=>'couponbindingcoupons',
                                'where'=>$input]);
        foreach($coupons as $coupon){
            $data   = $this->getCouponInfo(['coupon_id'=>$coupon->b_coupon_id]);

            if(isset($data)&&isset($data->code)&&$data->code!='01'&&(!isset($data->user_id)||$data->user_id=='')){
                $arr[] = $data;
            }else{
                $code = '01';
                break;
            }
        }

        if(count($arr)==0) $code = '01';
        return ['code'=>$code,'data'=>$arr];
    }

    /**
        获取优惠券面额
     */
    function get_coupon_price($input){
        $price = SQL::pluck(['table'=>'coupons',
                             'where'=>['coupon_id'=>$input],
                             'pluck'=>'price']);
        return $price;
    }

    /**
     * 删除优惠券
     */
    static function delete_channel_coupons($id){
        $channel = DB::table('channels')
                   ->where(['channel_id' => $id])
                   ->update(['state' => 0, 'updated_at' => time()]);
        $coupon  = DB::table('coupons')
                   ->where(['channel_id' => $id])
                   ->update(['state' => 0, 'updated_at' => time()]);
        return true;
    }

    /**
        后台
     */

    /**
        渠道编号获取优惠类型
     */
    function get_coupon_type_by_channel_id($input){
        $coupon_type = SQL::pluck(['table' => 'channels',
                                   'where' => $input,
                                   'pluck' => 'coupon_type']);
        return $coupon_type;
    }

    /**
        判断渠道是否已存在
     */
    function get_channel_maps_count($input){
        $count = SQL::count(['table' => 'channel_maps',
                             'where' => $input]);
        return $count;
    }

    /**
        添加使用范围
     */
    function insert_channel_maps($input){
        $input['created_at'] = time();
        $input['updated_at'] = $input['created_at'];
        $result = SQL::insert(['table'  => 'channel_maps',
                               'insert' => $input]);
        return $result;
    }

    /**
        判断资源是否可用
     */
    function resource_can_use($input){
        if($input['type'] != 1) return GeneralTool::createResult('','M05045');
        $is_exist = $this->productTempExistsByProdTempId($input['reg_id']);
        if(!$is_exist) return 'M05046';
        return 'M00000';
    }

    /**
        更新渠道使用范围
     */
    function update_channel_maps($input){
        $update = SQL::update(['table' => 'channel_maps',
                               'where' => $input['where'],
                               'update'=> $input['update']]);
        return $update;
    }

    /**
        适用范围id获取渠道编号
     */
    function get_channel_id_by_map_id($input){
        $channel_id = SQL::pluck(['table' => 'channel_maps',
                                  'where' => ['id' => $input],
                                  'pluck' => 'channel_id']);
        return $channel_id;
    }

    /**
        渠道编号获取渠道适用所有资源id
     */
    function get_resource_list_by_channel_id($input){
        $result = [];
        $result['product_temp'] = SQL::lists(['table' => 'channel_maps',
                                              'where' => ['channel_id' => $input,
                                                          'state'      => 1,
                                                          'type'       => 1],
                                              'lists' => 'reg_id']);
        return $result;
    }



    /**
        添加渠道适用范围
     */
    function add_channel_map($input){
        $true = $this->resource_is_true($input);
        if(!$true) return 'M05050';
        //判断资源是否已存在
        $count = $this->get_channel_maps_count(['channel_id' => $input['channel_id'],
                                                'type'       => $input['type'],
                                                'reg_id'     => $input['resource_id'],
                                                'state'      => 1]);
        if($count != 0) return 'M05051';
        $insert = SQL::insert(['table'  => 'channel_maps',
                               'insert' => ['channel_id' => $input['channel_id'],
                                            'type'       => $input['type'],
                                            'reg_id'     => $input['resource_id'],
                                            'quota'      => ($input['coupon_type'] == 1 && is_numeric($input['price']) ? $input['price'] : 0),
                                            'created_at' => time(),
                                            'updated_at' => time()]]);
        return $insert ? 'M00000' : 'M00001';
    }

    /**
     * 获取渠道下优惠券列表
     */
    function coupon_list_from_channel($input,$per_page = 10){
        $result = DB::table('coupons')
                  ->where(['channel_id' => $input['channel_id'],
                           'state'      => 1])
                  ->orderBy('user_id')
                  ->orderBy('using_time')
                  ->paginate($per_page);
        $result->appends($input)->render();
        return $result;
    }

    /**
     * 删除绑定
     */
    static function delete_banding($id){
        $arr   = SQL::lists(['table' => 'channelidbindingchids',
                             'where' => ['channel_id' => $id, 'state' => 1],
                             'lists' => 'b_channel_id']);
        $bind  = SQL::update(['table' => 'channelidbindingchids',
                              'where' => ['channel_id' => $id, 'state' => 1],
                              'update'=> ['state' => 0, 'updated_at' => time()]]);
        $coupon  = DB::table('coupons')
                   ->whereIn('channel_id', $arr)
                   ->update(['state' => 0]);
        return true;
    }

    /**
     * 获取活动详情
     */
    static function get_active_info($input){
        $result = SQL::first(['table' => 'actives',
                              'where' => $input]);
        return $result;
    }

    /**
     * 校验兑券资格wechat/check
     */
    static function verfy_code($input){
        $url    = env('WEI_SHOP_URL') . 'wechat/check';
        $str    = GeneralTool::createLinkstring($input);
        $result = GeneralTool::http_curl($url, $str, 1);
        if(isset($result['state']) && $result['state'] == 'M00000')
            return GeneralTool::createResult('', 'M00000');
        else
            return GeneralTool::createResult('', 'M05070');
    }

    /**
     * 活动优惠券奖池发放
     */
    static function coupon_pool_from_active($input){
        $channel = explode(',', $input['active']->coupons);
        if(!$channel || count($channel) == 0) return GeneralTool::createResult('', 'M05069');
        $new = [];
        for($a = 0;$a < count($channel); $a++){
            if(SQL::count(['table' => 'coupons',
                           'where' => ['channel_id' => $channel[$a],
                                       'user_id'    => '',
                                       'state'      => 1]]))
                $new[] = $channel[$a];
        }



        if(count($new) == 0) return GeneralTool::createResult('', 'M05069');


        $channel_id = DB::table('coupons')
                      ->where(['user_id'    => '',
                               'state'      => 1])
                      ->whereIn('channel_id',$channel)
                      ->inRandomOrder()
                      ->value('channel_id');
        if((strstr($channel_id, 'XMF') || strstr($channel_id, 'XMB')) &&
            SQL::count(['table' => 'coupons',
                       'where' => ['user_id'    => $input['user_id'],
                                   'channel_id' => $channel_id,
                                   'state'      => 1]]))
            return GeneralTool::createResult('', 'M05071');
        $coupon_id  = SQL::pluck(['table' => 'coupons',
                                  'where' => ['channel_id' => $channel_id,
                                              'user_id'    => '',
                                              'state'      => 1],
                                  'pluck' => 'coupon_id']);

        return GeneralTool::createResult(['coupon_id' => $coupon_id], 'M00000');
    }

    /**
        工具
     */
    /**
        判断资源是否有效
     */
    function resource_is_true($input){
        switch($input['type']){
            case 1:
                //产品模版
                return $this->productTempExistsByProdTempId($input['resource_id']);
            default:
                return false;
        }
    }
    /**
        获取对应资源类型
     */
    function get_type_by_input_type($input){
        switch($input){
            case 'product_temp':
                return 1;
            case 'product':
                return 2;
            case 'brand':
                return 3;
            default:
                return '';
        }
    }

    /**
        定时
     */

    //获取即将过期优惠券
    static function couponOverdue(){
        $time   = date('Y-m-d',time());
        $time   = strtotime($time);
        $channels= DB::table('channels')
                  ->where(['state'=>1])
                  ->whereBetween('end_time',[$time,$time+60*60*24])
                  ->pluck('channel_id');
        $users  = DB::table('coupons')
                  ->where(['using_time'=>0,'state'=>1])
                  ->whereIn('channel_id',$channels)
                  ->pluck('user_id');
        return $users;
    }


    /**
        其他类方法
     */
    /**
        商品是否可购买
     */
    function can_order($product_id, $colour_name, $size_name, $quantity, $user_id){
        return $this->productTool->can_order($product_id, $colour_name, $size_name,$quantity, $user_id);
    }
    /**
        商品编号获取商品价格 getCreatePrice
     */
    function get_product_price($input){

        $price = $this->productTool->get_preferential_price_by_product_id($input);
        return $price;
    }
    /**
        获取产品邮费
     */
    function get_postage_by_product_temp_id($input){
        return $this->productTool->get_postage_by_product_temp_id($input);
    }
    /**
        产品编号获取模版编号
     */
    function getTemplateByProductId($input){
        return $this->productTool->getTemplateByProductId($input);
    }
    /**
        产品模版编号获取品牌编号
     */
    function get_brand_id_by_prod_temp_id($input){
        return $this->productTool->get_brand_id_by_prod_temp_id($input);
    }
    /**
        产品编号获取模版价格
     */
    function get_product_temp_price_by_product_temp_id($input){
        return $this->productTool->get_product_temp_price_by_product_temp_id($input);
    }
    /**
        产品模版编号判断模版是否存在
     */
    function productTempExistsByProdTempId($input){
        return $this->productTempTool->productTempExistsByProdTempId($input);
    }
    /**
        品牌编号获取品牌名称
     */
    function getBrandNameByBrandId($input){
        return $this->brandToolService->getBrandNameByBrandId($input);
    }
    /**
        产品模版编号获取产品模版名称
     */
    function getProductTempNameByProductTempId($input){
        return $this->productTempTool->getProductTempNameByProductTempId($input);
    }
    /**
        获取所有产品模版信息
     */
    function getProductTempsByProductTempIds($input){
        return $this->productTempTool->getProductTempsByProductTempIds($input);
    }
}
